package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    //新增的时候插入
    @Override
    public void insertFill(MetaObject metaObject) {
        //新增创建时间
        this.strictInsertFill(metaObject,"createTime", Date.class, DateUtils.getNowDate());
        //新增创建人
        this.strictInsertFill(metaObject,"createBy",String.class,String.valueOf(getLoginUserId()));
    }
    //修改的时候插入
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新修改时间
        this.setFieldValByName("updateTime",DateUtils.getNowDate(),metaObject);
        //更新修改人
        this.setFieldValByName("updateBy",String.valueOf(getLoginUserId()),metaObject);
    }

    //定义一个方法，获取登录人的ID
    public Long getLoginUserId(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser != null){
            return loginUser.getUserId();
        }
        return null;
    }
}
